<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path:'/manage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>查看所有用户</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="w">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="用户类型">
          <el-select v-model="formInline.region" placeholder="请选择用户类型" @change="queryTypeChange">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="到期查询" v-show="queryTimeShow">
          <el-col :span="7">
            <el-date-picker type="date" placeholder="选择日期" v-model="formInline.date1" style="width: 100%;"/>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="7">
            <el-time-picker type="fixed-time" placeholder="选择时间" v-model="formInline.date2" style="width: 100%;"/>
          </el-col>
        </el-form-item>
        <el-form-item label="用户信息">
          <el-input v-model="formInline.user" placeholder="输入用户信息查询"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <!--表格方式-->
      <el-table
        :data="userList"
        style="width: 100%;margin-top: 10px;"
        :stripe="true"
        size="mini">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          label="姓名">
          <template slot-scope="scope">
            <div class="img_table"><img :src="scope.row.profilePhotoPath" alt="" width="40" height="40"></div>
            <p style="line-height: 40px;margin-left: 10px;float: left;">{{scope.row.nickname}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="realName"
          label="真实姓名">
        </el-table-column>
        <el-table-column
          width="120"
          label="版本">
          <template slot-scope="scope">
            <el-tag type="success" size="mini">{{scope.row.type === 1 ? '分销版' : '多门店分销版'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="60"
          label="性别">
          <template slot-scope="scope">
            <span>{{scope.row.type === 1 ? '男' : '女'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="角色">
          <template slot-scope="scope">
            <div>
              <el-tag v-for="role in scope.row.roles" :key="role.id" size="mini" style="margin-right: 10px;">
                {{role.name}}
              </el-tag>
              <el-popover
                placement="right"
                trigger="click"
                ref="checks">
                <el-checkbox-group v-model="roleCheck" size="mini" @change="checkChange">
                  <el-checkbox v-for="r in rolesList" :key="r.id" :label="r.id" border>{{r.name}}</el-checkbox>
                </el-checkbox-group>
                <el-button size="mini" type="primary" plain @click="subChange(scope.$index, scope.row.id, scope.row)" style="float: right;margin-top: 10px;">提交</el-button>
                <el-button v-if="scope.row.roles" type="text" size="mini" slot="reference" @click="toChange(scope.row.roles)">修改</el-button>
                <el-button v-else type="text" size="mini" slot="reference">分配角色</el-button>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="toUserDetail(scope.row.id)">查看详情</el-button>
            <el-popover
              v-if="scope.row.isAgent === 0"
              placement="top"
              width="180"
              trigger="click">
              <el-input v-model="rewardPoint" size="mini" placeholder="设置扣点数（单位千分）"/>
              <div style="text-align: right; margin: 10px 0 0">
                <el-button size="mini" type="text" @click="bodyClick">取消</el-button>
                <el-button type="primary" size="mini" @click="setAngent(scope.row.id)">确定</el-button>
              </div>
              <el-button slot="reference" size="mini" type="primary" style="margin-left: 10px;">设置代理商</el-button>
            </el-popover>
            <el-button size="mini" v-else type="danger" @click="delAgent(scope.row.id)">解除代理商</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 15, 20, 25]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: 'user-manage',
  data () {
    return {
      url: {
        agentSet: '/agent/set',
        cancel: '/agent/cancel'
      },
      options: [{
        value: '选项1',
        label: '分体'
      }, {
        value: '选项2',
        label: '代理商'
      }, {
        value: '选项3',
        label: '客服'
      }],
      tableData: [],
      formInline: {
        user: '',
        region: '选项1',
        data1: '',
        data2: ''
      },
      queryTimeShow: true,
      queryHave: false,
      // -------
      userList: [], // 解析完成后台返回的数据，用户列表
      roles: [], // 处理后的roles数据
      rolesList: [], // 原始roles数据
      roleRelations: [], // 用户有的roles数据
      roleCheck: [], // 复选框数据
      oldRoleCheck: [], // 复选框原始数据，最后提交比较用
      orRole: [], // 最后比较的数据，原始数据
      nowRole: [], // 最后比较的数据，最后数据
      // popShow: false // 角色修改显示隐藏
      rewardPoint: null,
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  methods: {
    bodyClick () {
      document.body.click()
    },
    checkChange (val) {
      // console.log(this.roleCheck)
      // console.log(this.oldRoleCheck)
    },
    // 设置代理商
    setAngent (id) {
      let params = {
        agentId: id,
        rewardPoint: this.rewardPoint
      }
      this.$ajax.post(this.url.agentSet, JSON.stringify(params)).then(res => {
        if (res.data.success) {
          this.$message.success('设置成功')
          this.getUserList()
          this.bodyClick()
        }
      })
    },
    // 解除代理商
    delAgent (id) {
      this.$confirm('是否取消代理商?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$ajax.post(this.url.cancel, id).then(res => {
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getUserList()
          }
        })
      })
    },

    onSubmit () {
      console.log('submit')
      console.log(this.formInline)
    },
    queryTypeChange (value) {
      console.log(value)
      if (value === '选项1') {
        this.queryTimeShow = true
      } else {
        this.queryTimeShow = false
      }
    },
    toChange (arr) {
      this.roleCheck = [] // 把上一次的置空
      this.oldRoleCheck = [] // 把上一次的置空
      arr.forEach((item, index) => {
        this.roleCheck.push(item.id)
        this.oldRoleCheck.push(item.id)
      })
    },
    // role/list userId
    subChange (index, id, row) {
      // this.$set(row, 'roles', [{name: 'zzf', id: 1}, {name: 'zz', id: 2}])
      // row.roles = [{name: 'zzf', id: 1}, {name: 'zz', id: 2}]
      this.nowRole = []
      this.orRole = []
      this.roleCheck.forEach((item, index) => {
        this.nowRole[item] = item
      })
      this.oldRoleCheck.forEach((item, index) => {
        this.orRole[item] = item
      })
      for (let i = 0; i < this.nowRole.length; i++) {
        if (this.orRole[i] === this.nowRole[i]) {
          this.orRole.splice(i, 1)
          this.nowRole.splice(i, 1)
          i--
        }
      }
      this.arrUtil(this.orRole)
      this.arrUtil(this.nowRole)
      // console.log(this.orRole, this.nowRole)
      let adds = this.nowRole
      let removes = this.orRole
      let params = {
        userId: id,
        adds,
        removes
      }
      if (!adds[0] && !removes[0]) {
        return
      }
      this.$ajax.post('/admin/manager/user/role/update', JSON.stringify(params)).then((res) => {
        if (res.data.success) {
          this.getUserRole(id, index)
          document.body.click() // 模拟点击事件，让框隐藏
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    getUserRole (id, index) {
      this.$ajax.post('/admin/manager/user/role/list', JSON.stringify(id)).then((res) => {
        this.userList[index].roles = res.data.data
      })
    },
    toUserDetail (id) {
      this.$router.push({path: '/admin/manager/user/userDetail', query: {id: id}})
    },
    arrUtil (arr) {
      for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === 'undefined' || arr[i] === '') {
          arr.splice(i, 1)
          i--
        }
      }
    },
    getUserList () {
      this.roleRelations = []
      this.userList = []
      this.rolesList = []
      this.roles = []
      let params = this.$route.query
      // 获取路由参数，判断是否有id，如果有，说明是从其他页面link过来的， 如果没有，说明是左侧导航栏过来的
      if (params.id) {
        // 路由参数中有id，发起Ajax请求，把id传给后台，返回此id的用户信息
        this.queryHave = true
      } // 路由参数中没有id，默认发起Ajax请求，后台返回所有分体用户信息，显示出来
      this.$ajax.all([
        this.$ajax.post('/admin/manager/user/list', {pageNum: this.page.pageNum, pageSize: this.page.pageSize}),
        this.$ajax.post('/admin/manager/permission/role/list')
      ]).then(this.$ajax.spread((userList, roleList) => {
        this.page.total = userList.data.data.pageInfo.total
        this.roleRelations = userList.data.data.roleRelations
        userList.data.data.pageInfo.list.forEach((item, index) => {
          this.userList[item.id] = item
          this.userList[item.id].roles = []
        })
        this.rolesList = roleList.data.data
        roleList.data.data.forEach((item, index) => {
          this.roles[item.id] = item
        })
        this.roleRelations.forEach((item, index) => {
          this.userList[item.userId].roles.push({
            name: this.roles[item.roleId].name,
            id: this.roles[item.roleId].id
          })
        })
        this.arrUtil(this.userList)
      }))
    },
    handleSizeChange (size) {
      this.page.pageSize = size
      this.getUserList()
    },
    handleCurrentChange (num) {
      this.page.pageNum = num
      this.getUserList()
    }
  },
  created () {
    this.getUserList()
  }
}
</script>

<style scoped>
  .img_table{
    width: 40px;
    height: 40px;
    border-radius: 100%;
    overflow: hidden;
    float: left;
  }
  .page{
    float: right;
    margin-top: 16px;
  }
</style>
